import { defineComponent, computed, ref } from 'vue'
import { NForm } from 'naive-ui'
import type { FormRules, FormInst } from 'naive-ui'
import type { PropType } from 'vue'

export default defineComponent({
  props: {
    inline: Boolean,
    labelWidth: null,
    labelAlign: null,
    labelPlacement: null,
    showFeedback: null,
    showLabel: null,
    showRequireMark: null,
    requireMarkPlacement: null,
    size: null,
    model: {
      type: Object,
      default: () => {
        return {}
      }
    },
    rules: {
      type: Object as PropType<FormRules>,
      default: () => {
        return {}
      }
    }
  },
  setup(props: any, { slots, expose }) {
    const formRef = ref<FormInst | null>(null)
    const params = computed(() => {
      const childerProps: any = {}
      if (props) {
        for (const propsKey in props) {
          if (props[propsKey] !== undefined) {
            childerProps[propsKey] = props[propsKey]
          }
        }
      }
      return childerProps
    })
    const validate = () => {
      return new Promise((rel: any) => {
        formRef.value?.validate(errors => {
          rel(errors)
        })
      })
    }
    expose({
      validate
    })
    return () => (
      <NForm ref={formRef} {...params.value}>
        {slots['default']?.()}
      </NForm>
    )
  }
})
